<template>
  <div class="setRoleMenu-dialog">
    <base-dialog :model="setData.isOpen" title="角色菜单" @close="handleClose">
      <template #body>
        <el-tree
          :data="menuList"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="menuTree"
          check-strictly
          :default-expanded-keys="[1, 2, 3, 4]"
          :default-checked-keys="roleMenuList"
          :props="defaultProps"
        >
        </el-tree>
      </template>
      <template #footer>
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addRoleMenu">确 定</el-button>
      </template>
    </base-dialog>
  </div>
</template>

<script>
import { getMenuList, getRoleMenuById, setRoleMenu } from '@/api/system'

export default {
  props: {
    setData: {
      type: Object
    }
  },
  data () {
    return {
      menuList: [],
      roleMenuList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  watch: {
    'setData.isOpen' (isOpen) {
      if (isOpen) {
        this.getMenus()
      }
    }
  },
  methods: {
    /* 获取菜单树 */
    getMenus () {
      getMenuList().then(res => {
        this.menuList = res.data
        this.getRoleMenu()
      })
    },
    /* 获取当前角色菜单 */
    getRoleMenu () {
      getRoleMenuById(this.setData.id).then(res => {
        this.roleMenuList = res.data
        this.$nextTick(() => {
          this.$refs.menuTree.setCheckedKeys(this.roleMenuList)
        })
      })
    },
    /* 添加角色菜单 */
    addRoleMenu () {
      const checkData = [...this.$refs.menuTree.getCheckedKeys(), ...this.$refs.menuTree.getHalfCheckedKeys()]
      const menuIdList = []
      if (checkData.length > 0) {
        Object.keys(checkData).forEach((key) => {
          menuIdList.push(checkData[key])
        })
      }
      const roleMenuInfo = { menuIdList, roleId: this.setData.id }
      setRoleMenu(roleMenuInfo).then(res => {
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.handleClose()
        this.$emit('successHandle')
      })
    },
    resetChecked () {
      this.$refs.menuTree.setCheckedKeys([])
    },
    /* 关闭弹窗 */
    handleClose () {
      this.setData.isOpen = false
    }
  }
}
</script>

<style lang="scss" scoped>
.setRoleMenu-dialog {
  .el-tree {
    min-height: 60vh;
  }
}
</style>
